from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from zope.app.component.hooks import getSite
from Products.CMFCore.utils import getToolByName

class frontView(BrowserView):
    template = ViewPageTemplateFile('templates/frontpage.html')

    def news(self):
        """
        retorna las 4 ultimas noticias del portal
        """
        miutils = utils(self.context)
        catalog = miutils.catalog
        results = catalog.searchResults(portal_type="News Item",sort_on="Date",sort_order="descending",sort_limit=6)
        return results

    def directory(self):
        """
        retorna el contenido de la carpeta directorio
        """
        miutils = utils(self.context)
        catalog = miutils.catalog
        site = miutils.portal
        siteId = site.getId()
        path = '/'+ siteId + '/guia-turistica'
        results = catalog.searchResults(path={'query':path,'depth':1},portal_type='Folder')
        return results

    def query(self,top,itemid,tipo):
        """
        Retorna el contenido de tipo guia de la carpeta
        itemid dentro de la carpeta top pasada por parametro
        """
        miutils = utils(self.context)
        catalog = miutils.catalog
        site = miutils.portal
        path = '/' + site.getId() + top + '/' + itemid
        results = catalog.searchResults(path={'query':path,'depth':1},portal_type=tipo)
        return results

    def query2(self,itemid):
        """
        Retorna el contenido de la carpeta itemid
        """
        miutils = utils(self.context)
        catalog = miutils.catalog
        site = miutils.portal
        path = '/' + site.getId() + '/' + itemid
        if itemid == 'vias-de-acceso':
            path = '/' + site.getId() + '/mi-municipio/' + itemid

        results = catalog.searchResults(path={'query':path,'depth':1},portal_type=('Atractivo','Pagina2','Folder'),
                                        sort_limit=4)
        return results[0:4]

    def actualidad(self,itemId):
        """funcion usado para la seccion de 
        Acutualidad"""
        miutils = utils(self.context)
        catalog = miutils.catalog
        site = miutils.portal
        path = '/' + site.getId() + '/' + itemId
        results = catalog.searchResults(path={'query':path,'depth':2},portal_type=('Clasificado','Social'),
                                        sort_limit=4,sort_on="Date",sort_order="descending")
        return results[0:4]

class utils:
     """
     Clase que declara objetos ocupados frecuentemente
     """
     def __init__(self,context):
        self.context = context
        self.catalog = getToolByName(self.context,'portal_catalog')
        self.portal = getSite()
        self.portalUrl = self.portal.absolute_url()